package cn.edu.njuit.webserver.securityserver.orders;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @Description: 订单队列操作服务
 * @Data: 2022/9/19 18:03
 * @Author: guzy
 */
@Service
public class OrderQueueService {
    private Log logger = LogFactory.getLog("队列服务");
    private final RabbitTemplate rabbitTemplate;

    public OrderQueueService(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 用户下单成功后，向队列1放入订单消息
     *
     * @param orderCode 订单号
     * @return
     */
    public boolean sendCreateMessage(String orderCode) {
        try {
            rabbitTemplate.convertAndSend("exchange.order", "confirm", orderCode);
            logger.info(String.format("向队列1：店家确认队列推送订单：%s", orderCode));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 店铺制作完成后，向队列2放入订单消息
     *
     * @param orderCode 订单号
     * @return
     */
    public boolean sendOrderDeliveMessage(String orderCode) {
        try {
            rabbitTemplate.convertAndSend("exchange.order", "delive", orderCode);
            logger.info(String.format("向队列2：待配送队列推送订单：%s", orderCode));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 骑手配送完成后或店家配送完成后，向队列4放入订单消息
     *
     * @param orderCode 订单号
     * @return
     */
    public boolean sendCompleteMessage(String orderCode) {
        try {
            rabbitTemplate.convertAndSend("exchange.order", "complete", orderCode);
            logger.info(String.format("向队列4：配送完成队列推送订单：%s", orderCode));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 手动从队列2中出队一条待配送订单用于骑手配送
     *
     * @return
     */
    public String reciveDeliveOrder() {
        //从队列2中获得一条消息
        Message msg = this.rabbitTemplate.receive("queue.order.delive");
        if (msg != null) {
            String orderCode = null;
            try {
                orderCode = new String(msg.getBody(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            logger.info(String.format("从队列2：待配送队列获取订单：%s", orderCode));
            return orderCode;
        } else {
            logger.info(String.format("队列2中无待配送订单"));
            return null;
        }
    }
}
